package com.sgu6.sgu6_machine.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.sgu6.netty.event.LoginAdminEvent;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseA;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.config.MachineConfig;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.db.DBManager;
import com.sgu6.sgu6_machine.dto.MachineLoginDto;
import com.sgu6.sgu6_machine.event.NetChangeEvent;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.util.NetUtil;
import com.sgu6.sgu6_machine.util.QRCodeUtil;
import com.sgu6.sgu6_machine.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginA extends BaseA {

    @BindView(R.id.tv_machine_no)
    TextView tvMachineNo;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.progress)
    ProgressBar progressBar;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.tv_back_time)
    TextView tvBackTime;

    String machineNo = "000-0000000";
    String machinePwd = "123456";

    MachineP machineP;
    int netStatus = NetUtil.NETWORK_NONE;
    @BindView(R.id.iv_login_code)
    ImageView ivLoginCode;
    private CountDownTimer timer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        machineNo = MachineContainer.machineConfigDto.machineNo;
        initUI();

        timer = new CountDownTimer(30*1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int s = (int) ((millisUntilFinished/1000));
                tvBackTime.setText(s+"秒后返回主页");
            }

            @Override
            public void onFinish() {
                finish();
            }
        };
        timer.start();
        clearPreDayData();
    }

    public void clearPreDayData() {
        try {
            DBManager.getInstance(this).clearCharge();
            DBManager.getInstance(this).clearVoltage();
            DBManager.getInstance(this).clearPower();
            DBManager.getInstance(this).clearEletric();
        } catch (Exception e) {
            Log.i(TAG, "clearPreDayData: " + e.getLocalizedMessage());
        }
    }

    private void initLogo() {
        RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).signature(new ObjectKey(System.currentTimeMillis()));
        File file = new File(Constant.FILE_ROOT_PATH + "/sgu6/images/", "logo.png");
        Glide.with(this).load(file).apply(options).into(ivLogo);
    }


    @Override
    public void initUI() {
        initToolbar();
        initMachineNo();
        initParams();
        initLogo();
        setLoginCode();
    }


    public void initParams() {
        machineP = new MachineP();
    }

    /**
     * 初始化机器id
     */
    private void initMachineNo() {
        tvMachineNo.setText(MachineContainer.machineConfigDto.machineNo);
    }


    private void initToolbar() {
        toolbar.setBackgroundResource(R.color.colorPrimaryDark);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }


    private void setLoginCode() {
        //http://admin-dev.sgu6.com/management/loginmachine?machineNo=test22222
        String url = "https://www.sgu6.com/machineLogin/machineLogin.html?machineNo=" + MachineContainer.machineConfigDto.machineNo;
        ivLoginCode.setImageBitmap(QRCodeUtil.createQRCodeBitmap(url, 300, 300));
    }

    @OnClick(R.id.tv_login)
    public void onClickLogin() {
        machinePwd = etPwd.getText().toString().trim();
        if (machinePwd.length() > 0) {
            if (netStatus == NetUtil.NETWORK_NONE) {
                if (MachineContainer.machineConfigDto.machinePassword.equals(machinePwd)) {
                    ToastUtil.show(LoginA.this, "登录成功");
                    startActivity(new Intent(this, MachineManagerA.class));
                    this.finish();
                } else {
                    ToastUtil.show(LoginA.this, "密码错误，请重试");
                }
            } else {
                machineP.login(machineNo, machinePwd);
                progressBar.setVisibility(View.VISIBLE);
            }

        } else {
            ToastUtil.show(LoginA.this, "密码不能为空");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogin(LoginAdminEvent event) {
        startActivity(new Intent(this, MachineManagerA.class));
        this.finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogin(MachineLoginDto dto) {
        Log.i(TAG, "onLogin: " + dto.isSucceed());
        progressBar.setVisibility(View.GONE);
        if (dto.isSucceed()) {
            ToastUtil.show(LoginA.this, "登录成功");
            try {
                MachineContainer.machineConfigDto.machineNo = machineNo;
                MachineContainer.machineConfigDto.machinePassword = machinePwd;
                machineConfig.updateMachineConfig(this);
            } catch (Exception e) {
                Log.i(TAG, "onLogin: 更新机器账号密码出错");
                e.printStackTrace();
            }
            startActivity(new Intent(this, MachineManagerA.class));
            this.finish();
        } else {
            if (dto.getErrMsg().length() == 0) {
                ToastUtil.show(LoginA.this, "登录失败，请重试！");
            } else {
                ToastUtil.show(LoginA.this, dto.getErrMsg());
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return true;
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        netStatus = NetUtil.getNetWorkState(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetChange(NetChangeEvent event) {
        Log.i(TAG, "onNetChange: " + event.netStatus);
        netStatus = event.netStatus;
    }
}
